/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import connexiondatabase.MySQLManager;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Hippolyte
 */
public class Jardin extends HashMap<Legume, Integer> implements Serializable {

    MySQLManager sql = new MySQLManager("Potager");

    public boolean initJardin() {

        if (this == null || this.isEmpty()) {
            this.initJardinSQL();
        }

        if (this == null || this.isEmpty()) {
            return initJardinDeserialisation();
        }
        return true;
    }

    public boolean initJardinDeserialisation() {

        try {
            FileInputStream fichier = new FileInputStream("jardin.ser");
            ObjectInputStream ois = new ObjectInputStream(fichier);
            Jardin deser = (Jardin) ois.readObject();
            System.out.println("nb de legumes desérialisés : " + deser.size());
            this.putAll(deser);
        } catch (java.io.IOException e) {
            System.out.println("IOException");
            return false;
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException");
            return false;
        }


        return true;
    }

    public boolean initJardinSQL() {

        if (!sql.connect()) {
            return false;
        }

        Legume l;

        Connection conn = sql.getConnection();
        try {
            Statement s = conn.createStatement();

            String query = "select j.nomLegume, qte, prix "
                    + "from jardin j, legume l "
                    + "where l.nomLegume = j.nomLegume";
            System.out.println(query);
            s.executeQuery(query);

            ResultSet rs = s.getResultSet();

            while (rs.next()) {
                l = new Legume(rs.getString("j.nomLegume"), rs.getInt("prix"));
                this.put(l, rs.getInt("qte"));
                System.out.println("add " + l.getNom() + " "
                        + l.getPrix() + " " + rs.getInt("qte"));
            }


        } catch (SQLException ex) {
            Logger.getLogger(Jardin.class.getName()).log(Level.SEVERE, null, ex);
            sql.disconnect();
            return false;
        }
        sql.disconnect();
        return true;
    }

    public boolean sauvJardin() {
        try {
            FileOutputStream fichier = new FileOutputStream("jardin.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fichier);
            oos.writeObject(this);
            oos.flush();
            oos.close();
        } catch (java.io.IOException e) {
//            System.out.println(e);
            System.out.println("cannot serialize jardin");
            return false;
        }
        return true;
    }

    public String initHTML() {

//        if (this == null || this.isEmpty()) {
//            initJardin();
//        }

        if (this == null || this.isEmpty()) {
            this.put(new Legume("Carotte", 2), 2);
            this.put(new Legume("Banane", 10), 8);
            this.put(new Legume("Poireau", 11), 9);
        }

        String retour = "";
        for (Legume l : this.keySet()) {
            retour += l.getNom() + " : <input type=\"text\" name=\"qt_"
                    + l.getNom() + "\">" + l.getPrix() + "€"
                    + "   (" + this.get(l) + " restants)<br/>";
        }
        return retour;
    }

    public Legume getLegume(String nom) {
        for (Legume l : this.keySet()) {
            if (l.getNom().equalsIgnoreCase(nom)) {
                return l;
            }
        }
        return null;
    }

    public int checkQuantite(Legume l, int qte) {

        if (qte > 0 && this.containsKey(l)) {
            return Math.min(qte, this.get(l));
        }
        return 0;
    }

    public int checkQuantite(Legume l, String qte) {

        int qt;
        if (qte == null || qte.isEmpty()) {
            return 0;
        }

        try {
            qt = Integer.parseInt(qte);
            return checkQuantite(l, qt);
        } catch (NumberFormatException nfe) {
            System.out.println(nfe);
            return 0;
        }
    }

    public void vendre(Legume l, int qte) {
        if (qte > 0) {
            int qteLegume = this.remove(l);
            int qteRestante = qteLegume - qte;
            if (qteRestante > 0) {
                this.put(l, qteRestante);
                updateLegumeInDb(l, qteRestante);
            } else {
                deleteLegumeInDb(l);
            }
        }
    }

    private boolean updateLegumeInDb(Legume l, int q) {
        
        if(q <= 0){
            deleteLegumeInDb(l);
        }

        if (!sql.connect()) {
            return false;
        }


        Connection conn = sql.getConnection();
        try {
            Statement s = conn.createStatement();
            String query = "update jardin set qte = " + q
                    + " where nomLegume = '" + l.getNom() + "'";
            System.out.println(query);
            s.executeUpdate(query);

        } catch (SQLException ex) {
            Logger.getLogger(Jardin.class.getName()).log(Level.SEVERE, null, ex);
            sql.disconnect();
            return false;
        }
        sql.disconnect();
        return true;
    }

    private boolean deleteLegumeInDb(Legume l) {

        if (!sql.connect()) {
            return false;
        }


        Connection conn = sql.getConnection();
        try {
            Statement s = conn.createStatement();

            String query = "delete from jardin where nomLegume = '" + l.getNom() + "'";
            System.out.println(query);
            s.executeUpdate(query);

        } catch (SQLException ex) {
            Logger.getLogger(Jardin.class.getName()).log(Level.SEVERE, null, ex);
            sql.disconnect();
            return false;
        }
        sql.disconnect();
        return true;
    }

    public boolean ajoutLegume(Legume l, int qte) {
        if (l == null || !this.containsKey(l)) {
            if (qte > 0) {
                this.put(l, qte);
                return ajoutLegumeInDb(l, qte);
            }
            
        } else{
            int oldQte = this.get(l);
            qte += oldQte;
            this.remove(l);
            if (qte > 0){
                this.put(l, qte);
            }            
            updateLegumeInDb(l, qte);
        }
        
        return true;

    }


    private boolean ajoutLegumeInDb(Legume l, int qte) {
        if (!sql.connect()) {
            return false;
        }


        Connection conn = sql.getConnection();
        try {
            Statement s = conn.createStatement();
            String query = "insert into legume (nomLegume, prix) values ( '"
                    + l.getNom() + "', '" + l.getPrix() + "')";
            System.out.println(query);
            s.executeUpdate(query);

            query = "insert into jardin (nomLegume, qte) values ( '"
                    + l.getNom() + "', '" + qte + "')";
            System.out.println(query);
            s.executeUpdate(query);

        } catch (SQLException ex) {
            Logger.getLogger(Jardin.class.getName()).log(Level.SEVERE, null, ex);
            sql.disconnect();
            return false;
        }
        sql.disconnect();
        return true;
    }
}
